package com.hulk.dryad.manage.limiter.expression;

import com.hulk.dryad.common.annotation.Limiter;
import com.hulk.dryad.manage.limiter.constant.LimiterInfo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.util.StringUtils;


/**
 * @author  hulk
 */
@Slf4j
@AllArgsConstructor
public class LimiterInfoResolver {

    public static final String LIMIT_NAME_PREFIX = "LIMITER";
	public static final String LIMIT_NAME_SEPARATOR = "$";


    private final LimiterKeyExpressionResolver limiterKeyExpressionResolver;

    public LimiterInfo get(JoinPoint joinPoint, Limiter limit) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        int  replenish =  limit.replenish();
		int  capacity =  limit.capacity();
        String keyName = limiterKeyExpressionResolver.getKeyName(joinPoint,limit);
        //按全类名拼接方法名
		String name= String.format("%s.%s", signature.getDeclaringTypeName(), signature.getMethod().getName());
        String limitName = LIMIT_NAME_PREFIX+LIMIT_NAME_SEPARATOR+name+(StringUtils.isEmpty(keyName)?"":LIMIT_NAME_SEPARATOR+keyName);
        log.debug("限流标识limitName:[{}]",limitName);
        return new LimiterInfo(limitName,replenish,capacity);
    }



}
